package com.youi.web;


import com.youi.common.Common;
import com.youi.common.SessionKey;
import com.youi.entity.MarketAdvertisement;
import com.youi.entity.Sysuser;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.MarketThemeAdvertisementService;
import com.youi.service.OperationlogService;
import com.youi.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

/**
 * 营销首页广告控制层
 *
 * @author jenran
 */
@RestController
@RequestMapping("/sysUserGetInfo")  //sysUserGetInfo
public class MarketThemeAdvertisementController extends HttpRequestManage {
    @Autowired
    private MarketThemeAdvertisementService marketThemeAdvertisementService;
    @Autowired
    private OperationlogService operationlogService;

    /**
     * I-
     * 根据id查询广告
     */
    @RequestMapping("getAdvertisementById")
    public String getAdvertisementById(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Long id = getLong("id", request);
        MarketAdvertisement marketAdvertisement = marketThemeAdvertisementService.get(id);
        if (marketAdvertisement == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此广告");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", marketAdvertisement);//jsonObject	json对象
    }

    /**
     * I-
     * 查询广告列表(条件搜索)
     */
    @RequestMapping("getAdvertisementList")
    public String getAdvertisementList(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        //查询已结束但状态未变更的广告变更结束状态
        marketThemeAdvertisementService.updateAdvertisementEndedStatus();

        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, Common.DESC);
        Map<String, Object> params = new HashMap();
        params.put(Common.DELSTATUS, 0);
        String name = optString("name", request);
        if (name == null) {
            name = "";
        }
        if (!name.equals("")) {
            params.put("name", name);
        }
        String code = optString("code", request);
        if (code == null) {
            code = "";
        }
        if (!code.equals("")) {
            params.put("code", code);
        }
        Integer status = optInteger(Common.STATUS, request);
        if (status != null) {
            params.put("status", status);
        }
        Integer position = optInteger("position", request);
        if (position != null) {
            if (position != 0) {
                params.put("position", position);
            }
        }
        //是否配置 0：全部 1：是 2：否
        Integer isSetting = optInteger("isSetting",request);
        if(isSetting != null){
            if(isSetting==1){
                params.put("position", Arrays.asList(1,2));
            }
            if(isSetting==2){
                params.put("position", 0);
            }
        }
        Date gmtEnabledStart=optDate("gmtEnabledStart",request,"yyyy-MM-dd HH:mm:ss");
        Date gmtEnabledEnd=optDate("gmtEnabledEnd",request,"yyyy-MM-dd HH:mm:ss");
        Date gmtBeginStart=optDate("gmtBeginStart",request,"yyyy-MM-dd HH:mm:ss");
        Date gmtBeginEnd=optDate("gmtBeginEnd",request,"yyyy-MM-dd HH:mm:ss");
        Map<String,Object> gtParams = null;
        Map<String,Object> ltParams = null;
        if(gmtEnabledStart!=null){
            if(gtParams==null){
                gtParams = new HashMap();
            }
            gtParams.put("gmtEnabled",gmtEnabledStart);
        }
        if(gmtBeginStart!=null){
            if(gtParams==null){
                gtParams = new HashMap();
            }
            gtParams.put("gmtBegin",gmtBeginStart);
        }
        if(gmtBeginEnd!=null){
            if(ltParams==null){
                ltParams = new HashMap();
            }
            ltParams.put("gmtBegin",gmtBeginEnd);
        }
        if(gmtEnabledEnd!=null){
            if(ltParams==null){
                ltParams = new HashMap();
            }
            ltParams.put("gmtEnabled",gmtEnabledEnd);
        }
        List<MarketAdvertisement> marketAdvertisementList = marketThemeAdvertisementService.getByParamsList(params, null, sortPram, (pageIndex - 1) * pageNum, pageNum, gtParams, ltParams);
        Integer pageCount = marketThemeAdvertisementService.getCountByParamss(params, null, null, null);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);            //pageIndex     查询页数
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, marketAdvertisementList);        //jsonObjectList json对象集合
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }


    /**
     * I-
     * 根据id删除广告
     */
    @RequestMapping("deleteAdvertisementByIds")
    public String deleteAdvertisementByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        String ids = getString("ids", request);
        Map<String, Object> params = new HashMap();
        if (ids != null && ids.trim().length() > 0) {
            List<Long> idsList = ObjectUtil.getIdListByIds(ids);
            if (idsList == null || idsList.size() == 0) {
                return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
            }
            params.put(Common.ID, idsList);
        } else {
            params.put(Common.ID, -1);
        }
        params.put(Common.DELSTATUS, 0);
        List<MarketAdvertisement> marketAdvertisementList = marketThemeAdvertisementService.getByParams(params);
        if (marketAdvertisementList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此广告");
        }
        for (MarketAdvertisement marketAdvertisement : marketAdvertisementList) {
            marketAdvertisement.setDelStatus(1);
        }
        marketThemeAdvertisementService.saveOrUpdateAll(marketAdvertisementList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * I-
     * 根据id变更广告状态
     */
    @RequestMapping("updateAdvertisementStatusByIds")
    public String updateAdvertisementStatusByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        String ids = getString("ids", request);
        Map<String, Object> params = new HashMap();
        if (ids != null && ids.trim().length() > 0) {
            List<Long> idsList = ObjectUtil.getIdListByIds(ids);
            if (idsList == null || idsList.size() == 0) {
                return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
            }
            params.put(Common.ID, idsList);
        } else {
            params.put(Common.ID, -1);
        }
        params.put(Common.DELSTATUS, 0);
        Integer status = getInteger(Common.STATUS, request);
        List<MarketAdvertisement> marketAdvertisementList = marketThemeAdvertisementService.getByParams(params);
        if (marketAdvertisementList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此广告");
        }
        for (MarketAdvertisement marketAdvertisement : marketAdvertisementList) {
            if (!(status == 1 || status == 2)) {
                return JsonUtil.toJson(CommonInfoUtil.ERROR, "禁止此状态的修改");
            }
            if (status == 1) {
                if (marketAdvertisement.getPosition() == 0) {
                    return JsonUtil.toJson(CommonInfoUtil.ERROR, "广告存在未配置状态，禁止启用");
                }
                marketAdvertisement.setGmtEnabled(new Date());
            }
            if (status == 2) {
                marketAdvertisement.setGmtDisabled(new Date());
            }

            marketAdvertisement.setStatus(status);
        }

        marketThemeAdvertisementService.saveOrUpdateAll(marketAdvertisementList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * I-
     * 添加或编辑广告信息(包括变更配置状态position)
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("addOrEditAdvertisement")
    public String addOrEditAdvertisement(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        synchronized ("edit") {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
//            Sysuser sysuser= new Sysuser();
//            sysuser.setId(Long.valueOf("1"));
//            sysuser.setType(0);  //测试用
            Long id = optLong("id", request);
            MarketAdvertisement marketAdvertisement = marketThemeAdvertisementService.get(id);
            if (marketAdvertisement == null) {
                id = null;
            }
            if (sysuser.getType() == 1) {
                return JsonUtil.toJson(CommonInfoUtil.OBJECTEXIST, "商家无权限编辑");
            }

            String name = getString("name", request);
            Integer position = optInteger("position", request);
            if (position == null) {
                position = 0;
            }
            String imgUrl = optString("imgUrl", request);
            String url = getString("url", request);
            Date gmtBegin = getDate("gmtBegin", request, "yyyy-MM-dd HH:mm:ss");
            Date gmtEnd = getDate("gmtEnd", request, "yyyy-MM-dd HH:mm:ss");
            String ip = IpUtil.getIpAddr(request);
            marketThemeAdvertisementService.addOrEditAdvertisement(id, marketAdvertisement, sysuser, ip, name, imgUrl, url, position, gmtBegin, gmtEnd);
            return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
        }
    }

}
